package org.gruposp2p.proyectokarma.controller

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.gruposp2p.proyectokarma.command.*;
import org.gruposp2p.proyectokarma.domain.KarmaFile;
import org.gruposp2p.proyectokarma.domain.Peer;
import org.hibernate.search.annotations.DateBridge;
import org.hibernate.search.annotations.Resolution;
import org.apache.commons.io.FileUtils;

class KarmaFileController {
	
	def springSecurityService

    def index = {
        //redirect(action:upload)
        render(view:"upload")
    }

   
   def upload = { UploadImageCommand command ->
	   //if(command.hasErrors()) {redirect(action:}
	   if (!command.contents.getOriginalFilename()) {
		   response.status = 400  //Bad Request
		   render message(code: 'proyectokarma.karmaFile.requestWithoutFile')
		   return
	   }
	   def maxFileSize = grailsApplication.config.image.maxFileSize
	   if (command.contents.size > maxFileSize) {
		   response.status = 400  //Bad Request
		   render message(code: 'proyectokarma.karmaFile.fileTooBig', args:[maxFileSize])
		   return
	   }
	   def userDetails = springSecurityService.principal
	   def peer = Peer.get(userDetails.id)
	   def file = KarmaFile.findWhere(peer:peer, name:command.contents.getOriginalFilename())
	   def webRootDir = servletContext.getRealPath("/")
	   def fileDir = grailsApplication.config.karmaFile.uploadDir
	   def userDir = new File(webRootDir, 
		   "/${fileDir}/${peer.id}")
	   userDir.mkdirs()
	   log.debug "userDir: " + userDir.getAbsolutePath()  + " - fileDir: " + fileDir
	   FileUtils.writeByteArrayToFile(
		   new File( userDir, command.contents.getOriginalFilename()), command.contents.bytes)
	   if (file) file.lastUpdated = new Date()
	   else {
	   		file = new KarmaFile(name: command.contents.getOriginalFilename(),
				   contentType:command.contents.getContentType(), peer:peer)
	   }
	   file.save()
	   response.status = 200
	   render message(code: 'proyectokarma.karmaFile.uploadOK', args:[command.contents.getOriginalFilename()])
	   return
   }
   
   def get = {
	   if (params.int("fileId")) {
		   def karmaFile = KarmaFile.get(params.int("fileId"))
		   if (!karmaFile) {
			   response.status = 404 //Not Found
			   render message(code: 'proyectokarma.karmaFile.fileNotFound', args:[params.int("fileId")])
			   return
			 }
		   def userDetails = springSecurityService.principal
		   def peer = Peer.get(userDetails.id)
		   if (!karmaFile.peer.id.equals(peer.id)) {
			   response.status = 404 //Not Found
			   render message(code: 'proyectokarma.karmaFile.fileNotFound', args:[params.int("fileId")])
			   return
		   }
		   def webRootDir = servletContext.getRealPath("/")
		   def filePath ="${webRootDir}/${grailsApplication.config.karmaFile.uploadDir}/${peer.email}/${karmaFile.name}"
		   response.setContentType(karmaFile.getContentType())
		   response.setHeader("Content-disposition", "filename=${karmaFile.getName()}")
		   response.outputStream << new File(filePath).getBytes() // Performing a binary stream copy
		   response.outputStream.flush()

	   } else {
	   		response.status = 404
			render message(code: 'proyectokarma.karmaFile.fileNotFound', args:[params.int("fileId")])
	   }
   }

   def delete = {
	   if (params.id) {
		   def karmaFile = KarmaFile.get(params.id)
		   if (karmaFile) karmaFile.delete()
		   else {
			   response.status = 404;
			   render message(code: 'proyectokarma.karmaFile.deleteNotFound', args:[params.id])
			   return
		   }
		   response.status = 200;
		   render message(code: 'proyectokarma.karmaFile.deleteOK', args:[params.id])
		   return
	   } else {
		   response.status = 400  //Bad Request
		   render message(code: 'proyectokarma.karmaFile.deleteBadRequest')
		   return;
	   }
   }
   
}